package com.nation.utils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Created by YeziAny on 2017/11/4.
 */
public class HandleZIP {
    public static int byteLength = 1024;
    public static String SEPARATOR=File.separator;
    //    国旗图片存储地址
    public static String NATIONALFLAGS="nationalFlags";//+SEPARATOR+"nationalFlags";
    //    国徽图片存储地址
    public static String NATIONALEMBLEMS="nationalEmbles";//+SEPARATOR+"nationalEmbles";
    // 区位地图
    public static String LOCATIONMAPS="locationMaps";
    // 国歌
    public static String NATIONALSONGS="nationalSongs";
//    上传国际统计数据的excel
    public static String INTERNATIONALDATAS="internationalDatas";

        /**
         * 解压zip文件
         * @param zipFile 要解压的zip文件对象
         * @param unzipFilePath 解压目的绝对路径
         * @throws IOException
         */
        @SuppressWarnings("all")
    public static List<String> unzip(File zipFile, String unzipFilePath, String folder) throws IOException {
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
//        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
//        存储解压的文件地址
        List<String> file_path=new ArrayList<String>();


        byte[] data = new byte[byteLength];

        // 创建解压后的文件夹
        File unzipDir = new File(unzipFilePath);
        if (!unzipDir.exists() || !unzipDir.isDirectory()) {
            unzipDir.mkdir();
        }

        // 解压
        for(Enumeration entries = zip.entries();entries.hasMoreElements();) {

            // 获取下一个解压文件
            ZipEntry zipEntry = (ZipEntry) entries.nextElement();
            System.out.println("系统正在解压："+zipEntry.getName());
            String currentFileName= ReadAndStoreFile.getZIPName(zipEntry.getName());
            if (currentFileName.equals("nationalFlags") || currentFileName.equals("pictureStore") || currentFileName.equals("locationMaps") ||currentFileName.equals("nationalSongs")){
                break;
            }else {
                String unzipEntryPath = unzipFilePath + "/" + ReadAndStoreFile.getZIPName(zipEntry.getName());
                System.out.println("正在解压de 文件路径："+unzipEntryPath);


                file_path.add(unzipEntryPath.substring(unzipEntryPath.indexOf("nation/"+folder)));

                int index = unzipEntryPath.lastIndexOf(HandleZIP.SEPARATOR);

                // 获取解压文件上层目录
                String unzipEntryDirPath;
                if (index != -1) {
                    unzipEntryDirPath = unzipEntryPath.substring(0, index);
                } else {
                    unzipEntryDirPath = "";
                }
                // 创建解压文件上层目录
                File unzipEntryDir = new File(unzipEntryDirPath);
                if (!unzipEntryDir.exists() || !unzipEntryDir.isDirectory()) {
                    unzipEntryDir.mkdir();
                }

                // 写出解压文件
                BufferedInputStream bis = new BufferedInputStream(zip.getInputStream(zipEntry));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(unzipEntryPath));
                while (bis.read(data, 0, byteLength) != -1) {
                    bos.write(data);
                }

                bis.close();
                bos.flush();
                bos.close();
            }
        }
        zip.close();
        System.out.println("******************解压完毕********************");
        return file_path;
    }
//    重载函数，保存国际信息上传zip中的excel表格
    public static List<String> unzip(File zipFile, String unzipFilePath) throws IOException {
        ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
//        Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
//        存储解压的文件地址
        List<String> file_path=new ArrayList<String>();


        byte[] data = new byte[byteLength];

        // 创建解压后的文件夹
        File unzipDir = new File(unzipFilePath);
        if (!unzipDir.exists() || !unzipDir.isDirectory()) {
            unzipDir.mkdir();
        }

        // 解压
        for(Enumeration entries = zip.entries();entries.hasMoreElements();) {

            // 获取下一个解压文件
            ZipEntry zipEntry = (ZipEntry) entries.nextElement();
            System.out.println("系统正在解压："+zipEntry.getName());
            String currentFileName= ReadAndStoreFile.getZIPName(zipEntry.getName());
            if (currentFileName.equals("internationalData")){
                break;
            }else {
                String unzipEntryPath = unzipFilePath + "/" + ReadAndStoreFile.getZIPName(zipEntry.getName());
                System.out.println("正在解压de 文件路径："+unzipEntryPath);


                file_path.add(unzipEntryPath);

                int index = unzipEntryPath.lastIndexOf(HandleZIP.SEPARATOR);

                // 获取解压文件上层目录
                String unzipEntryDirPath;
                if (index != -1) {
                    unzipEntryDirPath = unzipEntryPath.substring(0, index);
                } else {
                    unzipEntryDirPath = "";
                }
                // 创建解压文件上层目录
                File unzipEntryDir = new File(unzipEntryDirPath);
                if (!unzipEntryDir.exists() || !unzipEntryDir.isDirectory()) {
                    unzipEntryDir.mkdir();
                }

                // 写出解压文件
                BufferedInputStream bis = new BufferedInputStream(zip.getInputStream(zipEntry));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(unzipEntryPath));
                while (bis.read(data, 0, byteLength) != -1) {
                    bos.write(data);
                }

                bis.close();
                bos.flush();
                bos.close();
            }
        }
        zip.close();
        System.out.println("******************解压完毕********************");
        return file_path;
    }

    /**
     * 压缩文件
     * @param files 需要压缩的文件/目录
     * @param outFile 压缩输出地zip文件的名字
     * @return 压缩是否成功
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static boolean zip(File[] files, String outFile) throws FileNotFoundException, IOException{
        File file = new File(outFile);
        String zipPath = file.getAbsolutePath();
        zipPath = zipPath.substring(0, zipPath.length()-HandleZIP.SEPARATOR.length()-outFile.length());
        // 创建压缩文件
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(outFile);
        ZipOutputStream zos = new ZipOutputStream(fos);
        // 压缩
        pack(zipPath, files, zos);

        zos.close();
        return true;
    }

    /**
     * 打包文件/目录
     * @param srcPath zip文件的绝对路径
     * @param files 要打包的文件/目录
     * @param zos 已连接到zip文件的zip输入流实例
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void pack(String srcPath, File[] files, ZipOutputStream zos) throws FileNotFoundException, IOException {
        BufferedInputStream bis;
        ZipEntry ze;
        byte[] data = new byte[byteLength];

        for (File f : files) {
            // 递归压缩目录
            if (f.isDirectory()) {
                pack(srcPath, f.listFiles(), zos);
            } else if (f.getName().indexOf(".Ds_Store") != -1) {
                continue;
            } else {
                // 获取被压缩文件相对zip文件的路径
                String subPath = f.getAbsolutePath();
                int index = subPath.indexOf(srcPath);
                if (index != -1) {
                    subPath = subPath.substring(srcPath.length() + HandleZIP.SEPARATOR.length());
                }
                // 压缩文件
                ze = new ZipEntry(subPath);
                zos.putNextEntry(ze);
                bis = new BufferedInputStream(new FileInputStream(f));
                while (bis.read(data, 0, byteLength) != -1) {
                    zos.write(data);
                }
                bis.close();
                zos.closeEntry();
            }
        }
    }
}
